//
//  FZAlertController.m
//  Test
//
//  Created by Jianbo Cai on 2018/8/28.
//  Copyright © 2018年 JF. All rights reserved.
//

#import "FZAlertController.h"
#import <JFBase/JFBase.h>

#define RGB(r,g,b) [UIColor colorWithRed:r / 255.0 green:g / 255.0 blue:b / 255.0 alpha:1.0]
#define ActionDefaultColor RGB(252, 114, 76)
#define ActionCancleColor RGB(85, 85, 85)
#define ActionDestructiveColor [UIColor colorWithRed:0.58 green:0.58 blue:0.58 alpha:1.00]
#define AlertControllerHeight CGRectGetHeight([[UIScreen mainScreen] bounds])

#pragma mark - FZAlertController
@interface FZAlertController ()<UITextFieldDelegate>
{
    UIView *_contentView;
    UIView *_headerContentView; // 头部视图，包含标题或图片的
    CGRect contentViewRect;
    CGRect textScrollViewRect;
    CGRect menuScrollViewRect;
    
    UIEdgeInsets _contentMargin; // 默认边距
    CGFloat _contentViewWidth; // 默认alertView宽度
    CGFloat _maxHeight; // alertView的最大高度
    CGFloat _buttonHeight; // 默认按钮高度
    CGFloat _maxMenuHeight; // 按钮选项的最大高度
    CGFloat _textFieldHeight; // 默认输入框高度
    CGFloat _textFieldMargin; // 输入框之间的间距
    
    BOOL _firstDisplay;
    NSUInteger _count; // style == ZKAlertActionStyleCancel的action的数量
}

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIScrollView *textScrollView;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UIView *menuActionBgView;
@property (nonatomic, strong) NSMutableArray *mutableActions;
@property (nonatomic, strong) NSMutableArray *mutableTextFields;
@property (nonatomic, strong) UIButton *selectButton;
@property (nonatomic, strong) UIButton *closedButton;

@property (nonatomic, strong) void (^IndividualChoice)(UIButton *sender);

@end

@implementation FZAlertController

+ (instancetype)alertControllerWithTitle:(nullable NSString *)title message:(nullable NSString *)message
{
    return [self alertControllerWithTitleImage:nil title:title customView:nil message:message];
}

+ (instancetype)alertControllerWithImage:(nullable UIImage *)image message:(nullable NSString *)message
{
    return [self alertControllerWithTitleImage:image title:nil customView:nil message:message];
}

+ (_Nullable instancetype)alertControllerWithImage:(UIImage *)image title:(nullable NSString *)title customView:(nullable UIView *)customView {
    return [self alertControllerWithTitleImage:image title:title customView:customView message:nil];
}

+ (instancetype)alertControllerWithTitle:(nullable NSString *)title customView:(nullable UIView *)customView {
    return [self alertControllerWithTitleImage:nil title:title customView:customView message:nil];
}

+ (instancetype)alertControllerWithTitleImage:(UIImage *)image title:(NSString *)title customView:(nullable UIView *)customView message:(nullable NSString *)message
{
    FZAlertController *instance = [[FZAlertController alloc]init];
    instance.title = title;
    instance -> _image = image;
    instance -> _customView = customView;
    instance.message = message;
    return instance;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (instancetype)init
{
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self defaultConfig]; // 默认配置
    }
    return self;
}

#pragma mark -- life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    
    NSAssert(self.title.length || self.message.length || self.actions.count || self.textFields.count, @"ZKAlertController must have a title, a message or an action to display");
    
    /** 调整actions元素顺序 */
    [self adjustIndexesforActions];
    
    /** 创建基础视图 */
    [self creatContentView];
    
    /** 创建按钮 */
    [self creatAllButtons];
    
    /** 设置textScrollView的frame */
    [self configTextScrollViewFrame];
    
    /** 设置弹出框的frame */
    [self configContentViewFrame];
    
    /** 添加通知 */
    [self addNotification];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    /** 显示弹出动画 */
    [self showAppearAnimation];
}

#pragma mark -- 默认配置
- (void)defaultConfig
{
    _contentMargin = UIEdgeInsetsMake(20, 15, 15, 15);
    _maxHeight = AlertControllerHeight * 0.9;
    _contentViewWidth = CUSTOMVIEW_WIDTH;
    
    _buttonHeight = 45;
    _maxMenuHeight = _buttonHeight * 1.5;
    
    _textFieldHeight = 35;
    _textFieldMargin = 5;
    
    _messageAlignment = NSTextAlignmentCenter;
    _firstDisplay = YES;
    _choiceLoctionBottom = YES;
    _count = 0;
}

- (void)adjustIndexesforActions
{
    // 当只有两个action时，style == ZKAlertActionStyleCancel的action始终居左显示
    if (self.mutableActions.count == 2) {
        [self.mutableActions enumerateObjectsUsingBlock:^(FZAlertAction * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.style == UIAlertActionStyleCancel) {
                [self.mutableActions exchangeObjectAtIndex:idx withObjectAtIndex:0];
            }
        }];
    }
    
    // 当多于两个action时，style == ZKAlertActionStyleCancel的action始终居下显示
    if (self.mutableActions.count > 2) {
        [self.mutableActions enumerateObjectsUsingBlock:^(FZAlertAction *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.style == UIAlertActionStyleCancel) {
                [self.mutableActions removeObject:obj];
                [self.mutableActions addObject:obj];
            }
        }];
    }
}


#pragma mark -- 创建内部视图
- (void)creatContentView
{
    _contentView = [UIView new];
    _contentView.backgroundColor = [UIColor whiteColor];
    _contentView.layer.cornerRadius = 4;
    _contentView.clipsToBounds = YES;
    [self.view addSubview:_contentView];
    
    _headerContentView = [UIView new];
    _headerContentView.backgroundColor = [UIColor whiteColor];
    _contentView.clipsToBounds = YES;
    [_contentView addSubview:_headerContentView];
}

- (void)creatAllButtons
{
    CGFloat width = (self.actions.count == 1) ? 200 : (SCREEN_WIDTH == 320.0 ? 100 : 120);
    
    for (int i = 0; i < self.actions.count; i++) {
        FZAlertAction *button = self.actions[i];
        button.tag = 10 + i;
        [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.menuActionBgView addSubview:button];
        
        if (self.actions.count == 1) {
            button.frame = CGRectMake((_contentViewWidth - width) / 2, 10, width, 45);
        }else {
            CGFloat space = _contentViewWidth - 2 * (15 + width);
            button.frame = CGRectMake(i?(space + 15 + width):15, 10, width, 45);
        }
    }
    
    if (self.actions.count == 0) {
        self.menuActionBgView.height = 40;
    }
    
    if (self.selectButton && self.choiceLoctionBottom) {
        self.selectButton.frame = CGRectMake(15, 75, _contentViewWidth - 30, 20);
        self.menuActionBgView.height = 120;
        [self.menuActionBgView addSubview:self.selectButton];
    }
}


- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark -- 设置内部控件frame
- (void)configTextScrollViewFrame
{
//    CGFloat messageY = _contentMargin.top;
    CGFloat labelWidth = _contentViewWidth - _contentMargin.left - _contentMargin.right;
    
    // 内容textScrollView上添加视图
    {
        CGFloat textHeight = 25;
        if (self.image) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, textHeight, self.image.size.width, self.image.size.height)];
            [imageView setImage:self.image];
            [_headerContentView addSubview:imageView];
            imageView.frame = CGRectMake((_contentViewWidth - CGRectGetWidth(imageView.frame)) / 2, textHeight, CGRectGetWidth(imageView.frame), CGRectGetHeight(imageView.frame));
            
            UIImage *shadowImage = [UIImage imageNamed:@"ying_y"];
            UIImageView *shadow = [[UIImageView alloc]initWithFrame:CGRectMake(0, textHeight, shadowImage.size.width, shadowImage.size.height)];
            [shadow setImage:shadowImage];
            [_headerContentView addSubview:shadow];
            shadow.center = CGPointMake(_contentViewWidth / 2, CGRectGetMaxY(imageView.frame) + 6);
            textHeight = CGRectGetMaxY(shadow.frame) + 15;
        }
        
        if (self.title.length) {
            CGSize size = [self.titleLabel sizeThatFits:CGSizeMake(labelWidth, CGFLOAT_MAX)];
            self.titleLabel.frame = CGRectMake(_contentMargin.left, textHeight, labelWidth, size.height + 1);
            [_headerContentView addSubview:self.titleLabel];
            textHeight = CGRectGetMaxY(self.titleLabel.frame) + 15;
        }
        
        _headerContentView.frame = CGRectMake(0, 0, _contentViewWidth, textHeight);
        textHeight = 15;
        
        if (self.customView) {
            [self.textScrollView addSubview:self.customView];
            self.customView.frame = CGRectMake((_contentViewWidth - CGRectGetWidth(self.customView.frame)) / 2, 0, CGRectGetWidth(self.customView.frame), CGRectGetHeight(self.customView.frame));
            textHeight = CGRectGetMaxY(self.customView.frame) + 15;
        }
        
        if (self.message.length) {
            [self.textScrollView addSubview:self.messageLabel];
            CGSize size = [self.messageLabel sizeThatFits:CGSizeMake(labelWidth, CGFLOAT_MAX)];
            self.messageLabel.frame = CGRectMake(_contentMargin.left, textHeight, labelWidth, size.height);
            textHeight = CGRectGetMaxY(self.messageLabel.frame) + 15;
        }
        
        if (self.selectButton && !self.choiceLoctionBottom) {
            self.selectButton.frame = CGRectMake(15, textHeight, _contentViewWidth - 30, 20);
            [self.textScrollView addSubview:self.selectButton];
            textHeight = CGRectGetMaxY(self.selectButton.frame) + 15;
        }
        
        for (int i = 0; i < self.textFields.count; i++) {
            UITextField *textField = (UITextField *)self.textFields[i];
            textField.frame = CGRectMake(_contentMargin.left, textHeight + (_textFieldHeight + 5) * i, labelWidth, _textFieldHeight);
            [self.textScrollView addSubview:textField];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, _textFieldHeight - 0.5, labelWidth, 0.5)];
            line.backgroundColor = UIColorFromHex(0xE5E5E5);
            [textField addSubview:line];
            
            if (i == self.textFields.count - 1)
                textHeight = CGRectGetMaxY(textField.frame) + _contentMargin.bottom;
        }
        
        if (64 + textHeight + 90 <= _maxHeight) {
            self.textScrollView.frame = CGRectMake(0, CGRectGetMaxY(_headerContentView.frame), _contentViewWidth, textHeight);
        }else{
            self.textScrollView.frame = CGRectMake(0, CGRectGetMaxY(_headerContentView.frame), _contentViewWidth, _maxHeight - 200);
        }
        
        self.textScrollView.contentSize = CGSizeMake(_contentViewWidth, textHeight);
        
        textScrollViewRect = self.textScrollView.frame;

        
        if (self.showCloseBtn) {
            [self.view addSubview:self.closedButton];
        }
    }
}


- (void)configContentViewFrame
{
    self.menuActionBgView.y = CGRectGetMaxY(self.textScrollView.frame);
    
    _contentView.frame = CGRectMake(0, 0, _contentViewWidth, CGRectGetMaxY(self.menuActionBgView.frame));
    _contentView.center = self.view.center;
    
    _closedButton.center = CGPointMake(SCREEN_WIDTH / 2, CGRectGetMaxY(_contentView.frame) + 40);
    
    contentViewRect = _contentView.frame;
}

#pragma mark -- 事件响应
- (void)buttonDidClick:(UIButton *)sender
{
    [self.view endEditing:YES];
    
    FZAlertAction *action = self.actions[sender.tag - 10];
    
    [self dismissViewControllerAnimated:YES completion:^{
        if (action.actionHandler) action.actionHandler(action);
    }];
}

- (void)showAppearAnimation
{
    if (!_firstDisplay) return;
    
    _firstDisplay = NO;
    _contentView.transform = CGAffineTransformMakeScale(1.1, 1.1);
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.55 initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self -> _contentView.transform = CGAffineTransformIdentity;
    } completion:nil];
}

- (void)showDisappearAnimation
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 方法实现
- (void)addAction:(FZAlertAction *)action
{
    if (action.style == UIAlertActionStyleCancel) _count ++;
    
    NSAssert(_count < 2, @"ZKAlertController can only have one action with a style of ZKAlertActionStyleCancel");
    
    [self.mutableActions addObject:action];
}

- (void)addTextFieldWithConfigurationHandler:(void (^ __nullable)(UITextField *))configurationHandler
{
    UITextField *textField = [UITextField new];
    textField.delegate = self;
    textField.font = [UIFont fontWithName:@"PingFang SC" size: 14];
    textField.textColor = AWThemeColorForKey(@"Kit.DarkGrayTextColor");
    textField.borderStyle = UITextBorderStyleNone;
    textField.backgroundColor = AWThemeColorForKey(@"Kit.alertTextFieldBgColor");
    textField.clearButtonMode = UITextFieldViewModeAlways;
    textField.textAlignment = NSTextAlignmentCenter;
//    [textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.mutableTextFields addObject:textField];
    
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 17, 0)];
//    textField.leftView = view;
//    textField.leftViewMode = UITextFieldViewModeAlways;
    
    configurationHandler(textField);
}

- (void)addIndividualChoiceWithTitle:(NSString *)title configurationHandler:(void (^)(UIButton *))configurationHandler {
    UIButton *sender = [UIButton buttonWithType:UIButtonTypeCustom];
    sender.frame = CGRectMake(0, 0, CUSTOMVIEW_WIDTH, 20);
    NSString *buddleName;
    [sender setImage:[UIImage imageNameFromBuddle:@"icon_fenx_un" buddleName:buddleName] forState:UIControlStateNormal];
    [sender setImage:[UIImage imageNameFromBuddle:@"icon_fenx" buddleName:buddleName] forState:UIControlStateSelected];
    [sender setTitle:title forState:UIControlStateNormal];
    [sender setTitleColor:AWThemeColorForKey(@"IPO.cellTitleColor") forState:UIControlStateNormal];
    [sender addTarget:self action:@selector(individualChoiceAction:) forControlEvents:UIControlEventTouchUpInside];
    sender.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    sender.titleLabel.font = [UIFont fontWithName:@"PingFang SC" size: 14];
    self.selectButton = sender;
    self.IndividualChoice = configurationHandler;
    
    configurationHandler(sender);
}

#pragma mark -- 添加键盘通知
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardNotify:) name:UIKeyboardWillShowNotification object:nil];
}

#pragma mark -- 键盘通知接收处理
- (void)keyboardNotify:(NSNotification *)notify
{
    if ([UIViewController topViewController] != self) {
        return;
    }
    
    // 如果没有textfield，不做偏移
    
    NSValue *frameNum = [notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect rect = frameNum.CGRectValue;
    CGFloat keyboardHeight = rect.size.height + 5; // 键盘高度 + 5
    CGFloat keyboardMinY = rect.origin.y - 5; // 键盘y坐标 - 5
    
    CGFloat duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 获取键盘动画持续时间
    NSInteger curve = [[notify.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue]; // 获取动画曲线
    
    CGFloat marginBottom = AlertControllerHeight - CGRectGetMaxY(_contentView.frame);
    if (marginBottom >= keyboardHeight) return;
    
    CGFloat availableHeight = AlertControllerHeight * 0.95 - keyboardHeight;
    CGFloat alertViewMinX = CGRectGetMinX(contentViewRect);
    CGFloat alertViewWidth = CGRectGetWidth(contentViewRect);
    CGFloat alertViewHeight = CGRectGetHeight(contentViewRect);
    
    if (alertViewHeight <= availableHeight) {
        
        CGFloat alertViewMinY = keyboardMinY - alertViewHeight;
        
        [UIView animateWithDuration:duration delay:0 options:curve animations:^{
            
            self -> _contentView.frame = CGRectMake(alertViewMinX, alertViewMinY, alertViewWidth, alertViewHeight);
            
        } completion:nil];
        
    }else{
        
        CGFloat difference = keyboardHeight - (AlertControllerHeight * 0.95 - alertViewHeight);
        
        alertViewHeight -= difference;
        CGFloat alertViewMinY = AlertControllerHeight * 0.05;
        
        CGFloat textScrollViewMinX = CGRectGetMinX(textScrollViewRect);
        CGFloat textScrollViewMinY = CGRectGetMinY(textScrollViewRect);
        CGFloat textScrollViewWidth = CGRectGetWidth(textScrollViewRect);
        
        CGFloat menuScrollViewMinX = CGRectGetMinX(menuScrollViewRect);
        CGFloat menuScrollViewWidth = CGRectGetWidth(menuScrollViewRect);
        CGFloat menuMinHeight = CGRectGetHeight(menuScrollViewRect) < _maxMenuHeight ? CGRectGetHeight(menuScrollViewRect) : _maxMenuHeight;
        
        CGFloat menuMaxOffset = CGRectGetHeight(menuScrollViewRect) - menuMinHeight;
        CGFloat textScrollViewOffset = difference > menuMaxOffset ? difference - menuMaxOffset : 0;
        CGFloat textScrollViewHeight = CGRectGetHeight(textScrollViewRect) - textScrollViewOffset;
        CGFloat menuScrollViewMinY = CGRectGetMinY(menuScrollViewRect) - textScrollViewOffset;
        CGFloat menuScrollViewHeight = difference > menuMaxOffset ? menuMinHeight : CGRectGetHeight(menuScrollViewRect) - difference;
        
        [UIView animateWithDuration:duration delay:0 options:curve animations:^{
            self -> _textScrollView.frame = CGRectMake(textScrollViewMinX, textScrollViewMinY, textScrollViewWidth, textScrollViewHeight);
            self -> _menuActionBgView.y = CGRectGetMaxY(self -> _textScrollView.frame);
            self -> _contentView.frame = CGRectMake(alertViewMinX, alertViewMinY, alertViewWidth, alertViewHeight);
            
        } completion:nil];
    }
}

#pragma mark -- setter & getter
- (NSString *)title
{
    return [super title];
}

- (NSArray<FZAlertAction *> *)actions
{
    return [NSArray arrayWithArray:self.mutableActions];
}

- (NSArray<UITextField *> *)textFields
{
    return [NSArray arrayWithArray:self.mutableTextFields];
}

- (NSMutableArray *)mutableActions
{
    if (!_mutableActions) {
        _mutableActions = [NSMutableArray array];
    }
    return _mutableActions;
}

- (NSMutableArray *)mutableTextFields
{
    if (!_mutableTextFields) {
        _mutableTextFields = [NSMutableArray array];
    }
    return _mutableTextFields;
}

- (UIScrollView *)textScrollView
{
    if (!_textScrollView) {
        _textScrollView = [UIScrollView new];
        _textScrollView.backgroundColor = [UIColor whiteColor];
        _textScrollView.showsHorizontalScrollIndicator = NO;
        _textScrollView.autoresizesSubviews = NO;
        [_contentView addSubview:_textScrollView];
    }
    return _textScrollView;
}

- (UIView *)menuActionBgView {
    if (!_menuActionBgView) {
        _menuActionBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _contentViewWidth, 80)];
        _menuActionBgView.backgroundColor = [UIColor whiteColor];
        [_contentView addSubview:_menuActionBgView];
    }
    return _menuActionBgView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.numberOfLines = 0;
        _titleLabel.font = [UIFont boldSystemFontOfSize:17];
        _titleLabel.textColor = UIColorFromHex(0x333333);
        _titleLabel.text = self.title;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UILabel *)messageLabel
{
    if (!_messageLabel) {
        _messageLabel = [UILabel new];
        _messageLabel.numberOfLines = 0;
        _messageLabel.font = [UIFont systemFontOfSize:15];
        _messageLabel.textColor = UIColorFromHex(0x333333);
        if (_messageAttStr) {
            _messageLabel.attributedText = self.messageAttStr;
        }else {
            _messageLabel.text = self.message;
        }
        _messageLabel.textAlignment = self.messageAlignment;
    }
    return _messageLabel;
}

- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
    
    _titleLabel.text = title;
}

- (void)setMessage:(NSString *)message
{
    _message = message;
    
    _messageLabel.text = message;
}

- (void)setMessageAlignment:(NSTextAlignment)messageAlignment
{
    _messageAlignment = messageAlignment;
    
    _messageLabel.textAlignment = messageAlignment;
}

- (void)setMessageAttStr:(NSAttributedString *)messageAttStr {
    _messageAttStr = messageAttStr;
    _messageLabel.text = nil;
    _messageLabel.attributedText = messageAttStr;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)closeAction {
    WEAKSELF
    [self dismissViewControllerAnimated:YES completion:^{
        if (weakSelf.closeClick) {
            weakSelf.closeClick();
        }
    }];
}


-(void)textValueChanged:(UITextField *)textField
{
    FZAlertAction *action = self.actions[1];
    
    if (textField.text.length) {
        action.enabled = YES;
    }
    
    if (textField.text.length > 6) {
        
//      textField.text = [textField.text substringWithRange:NSMakeRange(0, 6)];
        
        NSString *currentString = textField.text;
        //获取当前的输入法语言，包括iOS自带的拼音输入法以及sogou，baidu中文输入法都涵盖在内
        NSString *currentLang = [[textField textInputMode] primaryLanguage];
          if ([currentLang containsString:@"zh-Hans"] == YES) {
              //获取高亮部分
              UITextRange *markedRange = [textField
                                          markedTextRange];
              UITextPosition *markedPosition = [textField
                                                positionFromPosition:markedRange.start
                                                offset:0];
              
              if (!markedPosition) {
                  if (currentString.length > 6) {
                    textField.text = [currentString substringToIndex:6];
                  }
              }
          }else{
              if (currentString.length > 6) {
                  textField.text = [currentString substringToIndex:6];
              }
          }
    }
}

- (void)individualChoiceAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    self.IndividualChoice(sender);
}

- (BOOL)agreedTo {
    return self.selectButton.isSelected;
}

+ (UIColor *)customViewBgColor {
    return [UIColor whiteColor];
}

- (UIButton *)closedButton {
    if (!_closedButton) {
        _closedButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closedButton setImage:[UIImage imageNamed:@"shut_down_icon"] forState:UIControlStateNormal];
        _closedButton.frame = CGRectMake(0, 0, 30, 30);
        [_closedButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closedButton;
}

@end
